package com.infonova.education.microservice.service.impl;

import com.infonova.education.microservice.repository.ProductRepository;
import com.infonova.education.microservice.repository.entity.Product;
import com.infonova.education.microservice.service.ProductService;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Override
    public List<Product> getAllProducts() {
        return (List<Product>) productRepository.findAll();
    }

    @Override
    public void saveProduct(Product product) {
        productRepository.save(product);
    }

    @Override
    public Long createProduct(Product product) {
        productRepository.save(product);
        return product.getId();
    }

    @Override
    public double priceForRegion(Long id, String region) {
     Product product=  productRepository.findOne(id);
     return product.getPricePerLocale(region);
    }

    @Override
    public Product getProduct(Long id) {
       return productRepository.findOne(id);
    }

    @Override
    public Long updateProduct(Long id, Product product) {
        Product oldProduct = productRepository.findOne(id);
        
        oldProduct.setName(product.getName());
        oldProduct.setAges(product.getAllowedAges());
        oldProduct.setPrices(product.getPrices());
        
        productRepository.save(oldProduct);
        
        return oldProduct.getId();
    }

    @Override
    public void deleteProduct(Long id) {
        if(productRepository.exists(id))
        {
            productRepository.delete(id);
        }
        else
        {
            System.out.println("PRODUKT NICHT VORHANDEN");
        }
    }

    @Override
    public List<Product> getAllowedProducts(int age, String locale) {
      Iterable<Product>all = productRepository.findAll();
      List<Product>allowedProducts = new LinkedList<Product>();
      Iterator iter = all.iterator();
      while(iter.hasNext())
      {
          Product pro = (Product) iter.next();
          if(pro.getAgePerLocale(locale)<=age)
          {
             allowedProducts.add(pro);
          }
      }
      
      return allowedProducts;
    
    }

    @Override
    public long nextID() {
        return productRepository.count()+1;
    }
    
    
    
    

}
